#include <stdio.h>
#include <stdlib.h>
#include "main_1.h"
#include "bitree.h"
#include "dlist.h"
#include "bistree.h"
#include "traverse.h"

//#define DATA_LEN 8

int mycompare(const void *key1, const void *key2) {
  int a = *(int *)key1;
  int b = *(int *)key2;
  if (a == b)
    return 0;
  else if (a < b)
    return -1;
  else
    return 1;
}

int bstree_to_dlist_main(int argc, char *argv[])
{
  if (argc < 2)
    exit(1);

  size_t const data_len = argc - 1;
  
  BisTree *bstree = NULL;
  
  bstree = (BisTree *)malloc(sizeof(BisTree));
  if (NULL == bstree)
    exit(-1);
  
  bistree_init(bstree, mycompare, free);

  int* mydata = (int *)calloc(data_len,  sizeof(int));
  
  printf("original data:\n");
  for (int i = 0; i < data_len; ++i) {
    mydata[i] = atoi(argv[i+1]);
    printf("%d ", mydata[i]);
  }
  
  int *avl_data = NULL;
  
  for (int i = 0; i < data_len; ++i) {
    avl_data = (int *)malloc(sizeof(int));
    if (NULL == avl_data)
      return -1;
    
    *avl_data = mydata[i];
    bistree_insert(bstree, (void *)avl_data);
  }


  DList *dlist=NULL;
  dlist = (DList *)malloc(sizeof(DList));
  if (NULL == dlist)
    return -1;
  
  dlist_init(dlist, free);

  inorder(bstree->root, dlist);

  printf("\nfrom head of the dlist:\n");
  for (BiTreeNode *plist_elmt = (BiTreeNode *)dlist->head;
       plist_elmt != NULL;
       plist_elmt = plist_elmt->right) {
    printf("%d ", *(int *)(((AvlNode *)(plist_elmt->data))->data));
  }

  printf("\nfrom tail of the dlist:\n");
  for (BiTreeNode *plist_elmt = (BiTreeNode *)dlist->tail;
       plist_elmt != NULL;
       plist_elmt = plist_elmt->left) {
    printf("%d ", *(int *)(((AvlNode *)(plist_elmt->data))->data));
  }

  printf("\n");
  
  return 0;
}

